//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Data;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CA = ComponentArt.Web.UI; 

namespace CommunityServer.ControlPanel.Photos
{
	/// <summary>
	///		Summary description for ManageCategoriesTreeControl.
	/// </summary>
	public class ManageCategoriesTreeControl : BaseGalleryControl
	{

		#region Public Properties

		private int categoryID = CSContext.Current.GetIntFromQueryString("CategoryID",0);
		public virtual int CategoryID
		{
			get{return categoryID;}
			set
			{
				categoryID = value;
				if(pageHasLoaded)
				{
					//SetSelectedNode(CategoryID);
				}
			}
		}

		#endregion

		#region Child Controls

		protected CommunityServer.ControlPanel.Controls.Hyperlink AddAlbumButton;
		protected CommunityServer.ControlPanel.Controls.Hyperlink DeleteAlbumButton;
        protected ComponentArt.Web.UI.TreeView TreeView1;   // using strongly typed name to avoid name conflict in asp.net 2.0

		#endregion

		bool pageHasLoaded = false;
		protected CommunityServer.ControlPanel.Controls.Hyperlink AddAlbumButtonCancel;
		protected CommunityServer.Controls.Modal Modal1;
	
		private bool IsAdministrator
		{
			get{return  CSContext.Current.User.IsGalleryAdministrator;}
		}

		const string CurrentURI = "CategoryManager.aspx?CategoryID={0}";

		protected string CurrentURL
		{
			get{return string.Format(CurrentURI, this.CategoryID); }
		}


		private void Page_Load(object sender, EventArgs e)
		{
			AjaxManager.Register(this,"ManageCategoriesTreeControl");

			if(!Page.IsPostBack)
			{
				buildTree();
			}
			pageHasLoaded=true;
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.TreeView1.NodeMoved += new ComponentArt.Web.UI.TreeView.NodeMovedEventHandler(this.TreeView1_NodeMoved);
			this.TreeView1.NodeSelected += new ComponentArt.Web.UI.TreeView.NodeSelectedEventHandler(this.TreeView1_NodeSelected);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void TreeView1_NodeSelected(object sender, CA.TreeViewNodeEventArgs e)
		{
			//updateSelectedPath(); 
			//OnPageChange(e);
			CSContext.Current.Context.Response.Redirect(GetURL(Globals.SafeInt(e.Node.ID,0)));
		}

		private void TreeView1_NodeMoved(object sender, CA.TreeViewNodeMovedEventArgs e)
		{
			PostCategory category = PostCategories.GetCategory(Globals.SafeInt(e.Node.ID,0), this.CurrentGallery.SectionID, true, true);
			if(e.Node.ParentNode != null)
				category.ParentID = Globals.SafeInt(e.Node.ParentNode.ID, 0);
			else
				category.ParentID = 0;
			PostCategories.UpdateCategory(category);
			//updateSelectedPath(); 
			OnPageChange(e);
		}

		private void buildTree()
		{
			ArrayList categories = PostCategories.GetCategories(CurrentGallery.SectionID, true, true, -1,true);
			PostCategory root = new PostCategory();
			root.Name = "\\";
			root.IsEnabled = true;

			categories.Add(root);

			DataTable dt = CADataConverter.ToDataTable(categories,typeof(PostCategory));

			foreach(DataRow dbRow in dt.Rows)
			{
				if(dbRow["CategoryID"].ToString() == "0")
				{
					dbRow["ParentID"] = DBNull.Value;
				}
			}
			

			DataSet ds = new DataSet();
			ds.Tables.Add(dt);
			ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["CategoryID"], ds.Tables[0].Columns["ParentID"]);

			foreach(DataRow dbRow in ds.Tables[0].Rows)
			{
				if(dbRow.IsNull("ParentID"))
				{          
					CA.TreeViewNode newNode = CreateNode(dbRow["CategoryID"].ToString(), dbRow["Name"].ToString(), CurrentGallery.IsActive, true);
					newNode.EditingEnabled = false;
					TreeView1.Nodes.Add(newNode);
					if(newNode.ID == categoryID.ToString())
						TreeView1.SelectedNode = newNode;
					PopulateSubTree(dbRow, newNode);
				}
			}
		}

		private void PopulateSubTree(DataRow dbRow, CA.TreeViewNode node)
		{
			foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
			{        
				CA.TreeViewNode childNode = CreateNode(childRow["CategoryID"].ToString(), childRow["Name"].ToString(), Globals.SafeBool(childRow["IsEnabled"].ToString(),true)  , true);
				node.Nodes.Add(childNode);
				if(childNode.ID == categoryID.ToString())
					TreeView1.SelectedNode = childNode;
				PopulateSubTree(childRow, childNode);
			}
		}

		private CA.TreeViewNode CreateNode(string categoryID, string text, bool enabled, bool expanded)
		{
			CA.TreeViewNode node = new CA.TreeViewNode();
			node.Text = text;//GetHREF(text, Globals.SafeInt(categoryID, 0)); 

			if(enabled)
				node.ImageUrl = "folder.gif"; 
			else
				node.ImageUrl = "folderdisabled.gif"; 
			node.Expanded = expanded;
			node.Attributes.Add("IsEnabled", enabled.ToString());
			node.Checked = enabled;
			node.ID = categoryID;
			return node;
		}

		public event EventHandler TreeChanged;

		protected void OnPageChange(EventArgs e)
		{
			if(TreeChanged != null)
				TreeChanged(this, e);
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public int ChangeCategoryEnabled(int categoryID)
		{
			if( !IsAdministrator ) 
				return -1;

			if(categoryID == 0)
			{
				CurrentGallery.IsActive = !CurrentGallery.IsActive;
				CommunityServer.Galleries.Galleries.Update(CurrentGallery); 
			}

			if(categoryID > 0)
			{
				PostCategory pc = PostCategories.GetCategory(categoryID,this.CurrentGallery.SectionID,true, true);

				if(pc != null)
				{
					pc.IsEnabled = !pc.IsEnabled;
					PostCategories.UpdateCategory(pc);
					
					//not cluster safe, but lets update the cache on this server anyways
					pc = PostCategories.GetCategory(categoryID,this.CurrentGallery.SectionID,true, true);
				}
			}
			return categoryID;
		}
		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public int RenameCategory(int categoryID, string newName)
		{
			if( !IsAdministrator ) 
				return 0;

			// Check to make sure it isn't a duplicate
			ArrayList categories = PostCategories.GetCategories(this.CurrentGallery.SectionID, true);
			
			foreach(PostCategory cat in categories)
			{
				if((cat.Name.ToLower() == newName) && (cat.CategoryID != categoryID) || categoryID == 0 )
				{
					/*ErrorLabel.Text = "<span style='color: red'>" + ResourceManager.GetString( "CategoryAdmin_Duplicate" ) + "</span>";
					ErrorLabel.Visible = true;
					Name.ForeColor = Color.Red;
					((RequiredFieldValidator)FindControl( "NameValidator" )).IsValid = false;
					*/
					//debugComment.Text = "Error '" + e.OldText + "' to '" + e.Node.Text + "'; duplicate name already exists in tree!"; 
					//Just set it back for now
					//e.Node.Text = e.OldText;
					return -1;
					
				}
			}

			PostCategory category = PostCategories.GetCategory(categoryID, this.CurrentGallery.SectionID , true);
			category.Name = HtmlScrubber.Clean(newName, false, true);
			PostCategories.UpdateCategory(category);
			//updateSelectedPath(); 
			
			return categoryID;

		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public int UpdateParentCategory(int categoryID, int parentCategoryID)
		{
			
			PostCategory category = PostCategories.GetCategory(categoryID, this.CurrentGallery.SectionID, true, true);

			if(category == null)
				return -1;

			if(parentCategoryID > 0)
				category.ParentID = parentCategoryID;
			else
				category.ParentID = 0;
			PostCategories.UpdateCategory(category);

			return 0;
		}
		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string AddCategory(int parentCategoryID)
		{

			if( !IsAdministrator ) 
				return "0";

			string name =  CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Photos_ManageCategories_NewCategoryString");
			// Check to make sure it isn't a duplicate
			ArrayList categories = PostCategories.GetCategories(this.CurrentGallery.SectionID, true, true, -1, true);
			name = PostCategories.NextCategoryName(categories, name);
	
			PostCategory category = new PostCategory() ;
			category.SectionID = this.CurrentGallery.SectionID;
			category.Name = HtmlScrubber.Clean(name, false, true);
			category.Description = string.Empty;
			if(parentCategoryID > 0)
				category.ParentID = parentCategoryID;
			category.IsEnabled = true;
			PostCategories.CreateCategory(category);

			return string.Format("{0}^{1}^{2}",category.CategoryID, category.ParentID, name) ;
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public int DeleteCategory(int categoryID)
		{
			if( !IsAdministrator ) 
				return 0;

			if(categoryID > 0)
			{
				PostCategory pc = PostCategories.GetCategory(categoryID,this.CurrentGallery.SectionID,true, true);

				if(pc.SectionID != CurrentGallery.SectionID)
					throw new CSException(CSExceptionType.SectionNotFound);
				if(pc != null)
					PostCategories.DeleteCategory(pc.CategoryID,pc.SectionID);
			}
			return categoryID;
		}
	
		private string GetURL(int categoryID)
		{
			return string.Format(CurrentURI, categoryID); 
		}


	}
}
